<template>
  <div>
    <!-- 进度条 -->
    <div class="progress-wrapper">
      <span class="time">{{ currentTime | timer(2) }}</span>
      <div class="progress-bar" ref="progressBar">
        <div class="progress-bar-go" ref="progressBarGo"></div>
        <div class="progress-bar-to" ref="progressBarto"></div>
        <div
          class="progress-bar-box"
          ref="progressBarBox"
          @touchstart="touchstart"
          @touchmove="touchmove"
          @touchend="touchend"
        ></div>
      </div>
      <span class="time">{{ currSong.duration | timer(2) }}</span>
    </div>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
export default {
  props: ["currentTime"],
  data() {
    return {
      touch: false,
    };
  },
  methods: {
    touchstart() {
      this.touch = true;
    },
    touchmove(e) {
      this.distance = e.touches[0].pageX - this.wrapperLeft;
      if (this.distance <= 0 || this.distance >= this.wrapperWidth)
        return false;
      this.move(this.distance);
    },
    touchend() {
      this.touch = false;
      let precent = this.distance / this.wrapperWidth;
      // 根据百分比计算时间
      let time = precent * this.currSong.duration;
      this.$emit("jump", time);
    },
    move(distance) {
      this.progress.style.width = distance + "px";
      this.boxBall.style.left = distance - 10 + "px";
    },
  },
  computed: {
    ...mapGetters(["currSong"]),
  },
  watch: {
    currentTime(newV) {
      if (this.touch) return false;
      let precent = newV / this.currSong.duration;
      let w = precent * this.wrapperWidth;
      this.move(w);
    },
  },
  filters: {
    timer(data, max) {
      let m = parseInt(data / 60);
      let strM = new Array(max - String(m).length + 1).join(0);
      let s = parseInt(data % 60);
      let strS = new Array(max - String(s).length + 1).join(0);
      return `${strM}${m}:${strS}${s}`;
    },
  },
  mounted() {
    this.wrapperLeft = this.$refs["progressBar"].getBoundingClientRect().left;
    this.wrapperWidth = this.$refs.progressBarGo.clientWidth;
    this.boxBall = this.$refs.progressBarBox;
    this.progress = this.$refs.progressBarto;
  },
};
</script>
<style lang="less" scoped>
@import "@styles/index.less";
.progress-wrapper {
  color: red;
  .wh(320,50);
  .padding(10,0,0,0);
  margin: 0 auto;
  display: flex;
  .progress-bar {
    .wh(220,30);
    position: relative;
    .margin(0,10,0,10);
    .progress-bar-go {
      .wh(220,4);
      background: gray;
      position: absolute;
      .top(12);
    }
    .progress-bar-to {
      //w长度和下面.left一样
      .h(5);
      background: @c;
      position: absolute;
      .top(12);
    }
    .progress-bar-box {
      .wh(10,10);
      .left(-10);
      border: 3px solid #fff;
      border-radius: 50%;
      background: @c;
      position: absolute;
      .top(6);
      //.left长度和上面w一样
    }
  }
  .time {
    .wh(40,30);
    color: #fff;
    .fs(12);
    .lh(30);
    flex: 1;
  }
}
</style>
